import type MarkdownIt from "markdown-it";
import container from "markdown-it-container";
import type Renderer from "markdown-it/lib/renderer.mjs";
import type Token from "markdown-it/lib/token.mjs";

interface ContainerOpts {
  marker?: string | undefined;
  validate?(params: string): boolean;
  render?(
    tokens: Token[],
    index: number,
    options: any,
    env: any,
    self: Renderer
  ): string;
}

export interface ContainerOptions {
  infoLabel?: string;
  noteLabel?: string;
  tipLabel?: string;
  warningLabel?: string;
  dangerLabel?: string;
  detailsLabel?: string;
  importantLabel?: string;
  cautionLabel?: string;
}

export const containerPlugin = (
  md: MarkdownIt,
  containerOptions?: ContainerOptions
) => {
  md.use(container, "demo", {
    render(tokens, idx) {
      const m = tokens[idx].info.trim().match(/^demo\s*(.*)$/);
      if (tokens[idx].nesting === 1 /* means the tag is opening */) {
        const description = m && m.length > 1 ? m[1] : "";
        const sourceFileToken = tokens[idx + 2];
        const sourceFile = sourceFileToken.children?.[0].content ?? "";

        return `<div><p>${description}</p><p>${sourceFile}</p>`;
      } else {
        return "</div>";
      }
    },
  } as ContainerOpts);
};
